import axios from 'axios'

export default {
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
  actions: {
    async initData (store) {
      const { data: res } = await axios.get(
        'http://www.itcbc.com:3006/api/cart'
      )
      store.commit('updateList', res.list)
    }
  },
  mutations: {
    updateList (state, val) {
      state.list = val
    },
    updateCount (state, obj) {
      //找到要修改数量的那个商品
      const row = state.list.find(item => item.id === obj.id)
      if (row.goods_count === 1 && obj.value === -1) return
      row.goods_count += obj.value
    },
    updateState (state, id) {
      //找到要修改数量的那个商品
      const row = state.list.find(item => item.id === id)
      row.goods_state = !row.goods_state
    },
    setAllState (state, boo) {
      state.list.forEach(item => {
        item.goods_state = boo
      })
    }
  },
  getters: {
    total (state) {
      //先找出所有选中状态的商品
      const a = state.list.filter(item => item.goods_state)
      return a.reduce((t, c) => t + c.goods_count, 0)
    },
    amount (state) {
      //先找出所有选中状态的商品
      const a = state.list.filter(item => item.goods_state)
      return a.reduce((t, c) => t + c.goods_count * c.goods_price, 0)
    },
    isFull (state) {
      return state.list.every(item => item.goods_state)
    }
  }
}
